package org.caijuan.transaction.questiontest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public void selfTransaction(String name) {
        this.nestedTransaction(name);
    }


    /**
     * 同类外层无事务，设置传播机制为 Propagation.REQUIRES_NEW
     * REQUIRES_NEW : 新启动一个事务，如果当前存在一个事务则将其挂起
     * 结论：不存在事务不会回滚
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void nestedTransaction(String name) {
        userRepository.save(new UserEntity(name));
        throw new RuntimeException("测试 REQUIRES_NEW 是否会滚回失败");
    }



    /**
     * 不开启事务但回滚
     * 结论：无事务，不回滚
     */
    public void hasNotTransactional(String name) {
        try {
            userRepository.save(new UserEntity(name));
            log.info("hasNotTransactional save  successful!");
            throw new RuntimeException("error");
        } catch (Exception ex) {
            log.error("create user failed", ex);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        log.info("result {} ", userRepository.findByName(name).size());
    }

    public int getUserCount(String name) {
        return userRepository.findByName(name).size();
    }

}
